package org.ly817.my.spring.core.aop;

import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 装饰器模式
 *
 * @author LuoYu
 * @date 2018/4/15
 */
public class JdkDynamicAopProxy implements AopProxy , InvocationHandler {

    private AdviceSupport adviceSupport;

    public JdkDynamicAopProxy(AdviceSupport adviceSupport) {
        this.adviceSupport = adviceSupport;
    }

    /**
     * 使用jdk java.lang.reflect.Proxy
     * Proxy.newProxyInstance动态代理：生成一个新类
     *
     * @return 代理对象
     */
    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(getClass().getClassLoader(),
                            adviceSupport.getTargetSource().getTargetInterface(),
                            this );
    }

    /**
     *
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MethodInterceptor methodInterceptor = adviceSupport.getMethodInterceptor();
        return methodInterceptor.invoke(new ReflectiveMethodInvocation(adviceSupport.getTargetSource().getTarget(), method, args));
    }
}
